import type { App } from "vue";
import type { I18nOptions } from 'vue-i18n'

import { createI18n } from 'vue-i18n'
import { setHtmlPageLang, setLoadLocalePool } from "./helper";
import { localeSetting } from '/@/settings/localeSetting';

import { useI18n } from '/@/hooks/web/useI18n';

export let i18n: ReturnType<typeof createI18n>;

const { fallback, availableLocales } = localeSetting;

async function createI18nOptions(): Promise<I18nOptions> {
  const locale = 'zh_CN'
  const defaultLocale = await import(`./lang/${locale}.ts`)
  const message = defaultLocale.default?.message ?? {};

  setHtmlPageLang(locale);
  setLoadLocalePool((loadLocalePool) => {
    loadLocalePool.push(locale);
  });

  return {
    // legacy: false,
    locale,
    fallbackLocale: fallback,
    messages: {
      [locale]: message
    },
    availableLocales: availableLocales,
    sync: true,
    silentTranslationWarn: true,
    missingWarn: false,
    silentFallbackWarn: true,
  }
}

export async function setupI18n(app: App) {
  const options = await createI18nOptions();
  i18n = createI18n(options)
  app.use(i18n)

  app.config.globalProperties.t = useI18n().t
}